/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package midpmpc;
import javax.microedition.io.*;
import java.io.*;
import java.util.Hashtable;
import org.j4me.logging.Log;

/**
 *
 * @author vvs
 */
public class MpdConnection {
static StreamConnection mpdConn;
static DataInputStream is;
static DataOutputStream os;
Mpc m;

    public MpdConnection(Mpc parent) {
        m=parent;
    }

static synchronized public String connect(String addr) throws IOException
{
    mpdConn=(StreamConnection)Connector.open("socket://"+addr);
    is=mpdConn.openDataInputStream();
    os=mpdConn.openDataOutputStream();
    return getLine();

}
static synchronized String getLine() throws IOException
{
    int tb,ttb=0;
    boolean multibyte=false;
    char tchar;
    String ret="";
    while ((tb=is.readByte())!='\n')
    {
        if(tb<0)
            tb+=256;
        //Log.warn(String.valueOf(tb));
        if (multibyte)
        {
            tchar=(char)((ttb*64)+tb-128);
            //Log.warn("multibyte "+String.valueOf(ttb)+ " "+String.valueOf(tb)+
            //        " "+(int)tchar);
            ret+=tchar;
            multibyte=false;
        }

        else
        {
            if (tb>127)
            {
                multibyte=true;
                //Log.warn("multibyte char1: "+String.valueOf(tb));
                ttb=tb-0x80-0x40;
            }
            else
                ret+=(char)tb;
        }
    }
//    m.message(ret);
//    m.debug(ret);
    return ret;
}
static synchronized public MpdResponse sendCmd(String cmd)
{
    Log.warn("sendCmd: "+cmd);
    String ret = "", ts = "";
    try {
        os.write(cmd.getBytes("utf-8"));
        os.write('\n');
        os.flush();
        while (!((ts = getLine()).startsWith("OK"))) {
            if (ts.startsWith("ACK ["))
            {
                Log.error("MPD error: '"+ts+"'");
                return new MpdResponse("");
            }
            // FIXME
            ret += ts;
            ret += '\n';
        }
    }
    catch (IOException exc) {
        Log.error("sendCmd: ",exc);
    }
    return new MpdResponse(ret);
}
public Hashtable status() throws IOException
{
    Hashtable ret =new Hashtable();
    MpdResponse resp=sendCmd("status");
    ret.put("state", resp.getString("state"));
    return ret;
}

}


